package com.amigo.online.provider.adv.interceptor;

import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.amigo.online.common.base.security.LocalUser;
import com.amigo.online.provider.adv.entity.RequestLog;
import com.amigo.online.provider.adv.mongo.dao.LoggerDao;
import com.amigo.online.provider.adv.util.LoggerUtil;


/**
 * @version: V 1.0.0
 * @Description: （日志拦截类）
 * @author: zxy  QQ:1363320658
 * @date: 2018年12月3日 上午11:15:15
 */
@Component
public class LoggerInterceptor extends HandlerInterceptorAdapter {

    public static String LOGGER_MODEL = "requestLog";

    private final Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

    @Autowired
    LoggerDao loggerDao;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        LocalUser.removeUser();
        RequestLog requestLog = (RequestLog) request.getAttribute(LOGGER_MODEL);
        long currentTimeMillis = System.currentTimeMillis();
        requestLog.setEndTime(currentTimeMillis);
        requestLog.setDuration(currentTimeMillis - requestLog.getStartTime());
        requestLog.setStatus(response.getStatus());
        logger.info(requestLog.toString());
        //loggerDao.saveRequestLog(requestLog);
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        method.getName();
        method.getReturnType();
        logger.info("Accept-Language:" + request.getHeader("Accept-Language"));
        logger.info("accept-language:" + request.getHeader("accept-language"));
        request.setAttribute(LOGGER_MODEL, getRequestLog(request));
        return true;
    }

    private RequestLog getRequestLog(HttpServletRequest request) {
        RequestLog requestLog = new RequestLog();
        requestLog.setParamData(JSON.toJSONString(request.getParameterMap(),
                SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue));
        requestLog.setMethod(request.getMethod());
        requestLog.setUrl(request.getRequestURI());
        requestLog.setSessionId(request.getRequestedSessionId());
        requestLog.setIp(LoggerUtil.getCliectIp(request));
        Enumeration<String> headerEnum = request.getHeaderNames();
        Map<String, String> requestHeaderMap = new HashMap<>();
        while (headerEnum.hasMoreElements()) {
            String headerName = (String) headerEnum.nextElement();
            requestHeaderMap.put(headerName, request.getHeader(headerName));
        }
        requestLog.setHeaderMap(requestHeaderMap);
        return requestLog;
    }

}
